package com.noodles.mall.controller;

import com.noodles.mall.entity.ItemImage;
import com.noodles.mall.service.ItemImageService;
import com.noodles.mall.util.Upload;
import com.noodles.mall.web.JsonResult;
import com.noodles.mall.web.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/** 商品轮播图 **/
@RestController
@RequestMapping("/item-image")
public class ItemImageController {
    private static String dir="item-image";

    @Autowired
    Upload upload;

    @Autowired
    private ItemImageService itemImageService;

    /** 增加 **/
    @RequestMapping("/upload/{itemId}")
    public JsonResult upload(@RequestBody MultipartFile file,
                             @PathVariable(value = "itemId") Integer itemId) {
        System.out.println("ItemImageController: upload");
        System.out.println("file: "+file);
        System.out.println("itemId: "+itemId);
        String imageUrl= upload.save(file,dir+"/"+itemId);
        ItemImage itemImage=itemImageService.insert(itemId,imageUrl);
        return itemImage!=null
                ? JsonResult.success(itemImage) : JsonResult.error(State.ERR_SQL);
    }

    /** 删除:  **/
    @RequestMapping("/delete")
    public JsonResult delete(@RequestBody List<Integer> ids){
        System.out.println("ItemImageController: delete");
        System.out.println("ids: "+ids);
        ItemImage itemImage=itemImageService.delete(ids.get(0));
        return itemImage == null ? JsonResult.error(State.ERR_SQL)
                : upload.delete(itemImage.getImageUrl())
                ? JsonResult.success() : JsonResult.error(State.ERR_NOTFOUND);
    }

    /** 查询列表: 商品id **/
    @RequestMapping("/selectList/{itemId}")
    public JsonResult selectList(@PathVariable(value = "itemId") Integer itemId) {
        System.out.println("ItemImageController: selectList");
        System.out.println("itemId: "+itemId);
        List<ItemImage> itemImageList = itemImageService.selectList(itemId);
        return JsonResult.success(itemImageList);
    }


}
